package com.xebest.web.controller.salesBill;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.constant.XeConstans;
import com.xebest.util.RequestUtil;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.web.form.XeVenFinSalesBillForm;
import com.xebest.web.model.XeVenFinSalesBillEntity;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenFinSalesBillService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenFinSalesBillView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("xeVenFinSalesBill")
@Scope("prototype")
public class XeVenFinSalesBillController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenFinSalesBillController.class);

    /**
     * 收款单业务操作
     */
    @Autowired
    private XeVenFinSalesBillService xeVenFinSalesBillService;


    /**
     * 收款单列表
     *
     * @auther wangyp
     */
    @RequestMapping("queryXeVenFinSalesBillList")
    public @ResponseBody
    BaseResponse queryXeVenFinSalesBillList(@RequestBody XeVenFinSalesBillForm form) {
        log.info("收款单列表入参" + JSONArray.toJSONString(form));
        //验证参数
        if (null == form) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //拼装参数
        XePageInfo<XeVenFinSalesBillView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        setSendTime(form);
        //输出结果
        List<XeVenFinSalesBillView> salesBillList = this.xeVenFinSalesBillService.queryXeVenFinSalesBillList(form);
        try {
            xePageInfo = new XePageInfo<XeVenFinSalesBillView>(salesBillList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("salesBillList", salesBillList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("收款单查询List异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 设置查询时间
     *
     * @param form
     */
    private void setSendTime(XeVenFinSalesBillForm form) {
        if (null != form.getSearchTimeType()) {
            switch (form.getSearchTimeType()) {
                case 1:
                    break;
                case 2:
                    form.setStartReceiveTime(form.getEndReceiveTime());
                    form.setEndReceiveTime(form.getStartReceiveTime());
                    form.setStartSendTime(null);
                    form.setEndSendTime(null);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 修改收款单信息
     *
     * @auther wangyp
     */
    @RequestMapping("updateFinSalesBil")
    public @ResponseBody
    BaseResponse updateFinSalesBil(@RequestBody XeVenFinSalesBillForm form) {
        try {
            log.info("修改收款单信息入参" + JSONArray.toJSONString(form));
            //验证参数
            if (null == form.getRealSbillAmount()
                    || StringUtils.isBlank(form.getSbillRemark())
                    || StringUtils.isBlank(form.getSbillCode())
                    || null == form.getEpayReceAmt()) {
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            //拼装参数
            form.setUserCode(userInfo.getUserCode());
            form.setModfiyUser(userInfo.getLoginName());
            if (form.getRealSbillAmount().compareTo(form.getEpayReceAmt()) == 0) {
                form.setSbillStatus(3);
            } else if (form.getRealSbillAmount().compareTo(form.getEpayReceAmt()) == -1) {
                form.setSbillStatus(2);
            }
            //修改收款单信息
            int result = xeVenFinSalesBillService.updateXeVenFinSalesBill(form);
            //添加操作日志
            String ipAddress = RequestUtil.getClientIpAddress(request);
            String logType = ErpLogTypeEnum.erpFinSalesBillUpdate.getValue();
            StringBuffer operatorContent = new StringBuffer();
            String userCode = userInfo.getUserCode();
            String userName = userInfo.getUserName();
            operatorContent.append("编辑收款单号为" + form.getSbillCode() + "修改实收金额为:“￥" + form.getRealSbillAmount()
                    + "”，备注内容为:" + form.getSbillRemark() + "。");
            OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, form.getSbillCode(), logType, userName, operatorContent.toString(), userCode);

            if (result == XeConstans._XE_ONE) {
                return sendAjaxOK();
            } else {
                return sendAjaxError();
            }
        } catch (Exception e) {
            log.error("付款单信息修改异常：{}", e);
            return sendAjaxError();
        }
    }

    @RequestMapping("saveBill")
    public BaseResponse saveBill(@RequestBody XeVenFinSalesBillEntity entity) {
        log.debug("添加付款单列表请求参数为：{}", JSON.toJSONString(entity));
        //验证参数
        if (null == entity) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }

        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        entity.setUserCode(userInfo.getUserCode());
        int result = 0;
        try {
            //添加付款单
            result = this.xeVenFinSalesBillService.saveFinSalesBill(entity);

            if (result <= 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("添加付款单失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }


}
